
package com.imooc.sell.controller;

import com.google.gson.JsonObject;
import com.imooc.sell.VO.tian.fore.CategoryResult;
import com.imooc.sell.VO.tian.newUtil.ResultUtil;
import com.imooc.sell.VO.tian.newUtil.ResultVo;
import com.imooc.sell.dataobject.ProductCategory;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.dataobject.query.ProductQuery;
import com.imooc.sell.service.impl.CategoryServiceImpl;
import com.imooc.sell.service.impl.ProductInfoServiceImpl;
import com.imooc.sell.utils.CharacterUtil;
import com.imooc.sell.utils.ImageUtil;
import com.imooc.sell.utils.UploadedImageFile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName AdminController
 * @Description 后台管理
 * @Author tianli
 * @Date 2018/8/16
 **/
@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    ProductInfoServiceImpl productInfoService;

    @Autowired
    CategoryServiceImpl categoryService;

    private Date createTimeForAdmin = null;

    private Date endTimeForAdmin = null;

    private Integer sortCodeForAdmin = null;

    @RequestMapping("/test")   //查询所有分类
    public String test(Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "2") int size) {
        return "test";
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author tianli
     * @Description 后台返回商品列表
     * @Date 2018/8/16
     **/
    @RequestMapping("/productlist")
    public ModelAndView adminProductList(String openid, @RequestParam(value = "page", defaultValue = "1") int start, @RequestParam(value = "size", defaultValue = "2") int size, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();

        start = start < 0 ? 0 : start;
        Sort sort = new Sort(Sort.Direction.ASC, "createTime"); //设置根据id升序排列
        Pageable pageable = new PageRequest(start - 1, size, sort); //根据start、size、sort创建分页对象
        Page<ProductInfo> page = productInfoService.findAll(pageable);

        modelAndView.setViewName("productlist");
        modelAndView.addObject("sortCode", 2);
        modelAndView.addObject("page", page);
        modelAndView.addObject("currentPage", start - 1);
        modelAndView.addObject("size", size);
        modelAndView.addObject("openid", openid);
        return modelAndView;
    }

    /**
     * @param id 商品id
     * @return java.lang.String 商品列表
     * @Author tianli
     * @Description 商品删除
     * @Date 2018/8/14
     **/
    @RequestMapping("/productdelete")
    @ResponseBody
    public String deleteProduct(String openid, @RequestParam String id, HttpServletRequest request) {
        JsonObject jsonObject = new JsonObject();
        ProductInfo productInfo = productInfoService.findOne(id);
        //服务端需要删除图片
        String imageFolder = null;
        try {
            imageFolder = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File file = new File(imageFolder, "static/images/");
        File f_detail = new File(file, productInfo.getProductIcon() + ".jpg");
        f_detail.delete();
        if (productInfoService.delete(id)) {
            jsonObject.addProperty("msg", 1);//删除成功
        } else {
            jsonObject.addProperty("msg", 0);//删除失败
        }
        jsonObject.addProperty("openid", openid);
        return jsonObject.toString();
    }

    /**
     * @param productInfo       获取到的商品
     * @param uploadedImageFile 获取到的相片
     * @return java.lang.String 商品列表
     * @Author tianli
     * @Description 添加商品, 修改商品
     * @Date 2018/8/14
     **/
    @PostMapping("/productadd")
    @ResponseBody
    public String addProduct(String openid, ProductInfo productInfo, UploadedImageFile uploadedImageFile, HttpServletRequest request) {
        String fileName = CharacterUtil.getRandomString(32);
        //随机设置图片存储名字
        productInfo.setProductIcon(fileName);
        fileName = fileName + ".jpg";
        //服务端需要存储图片
        String imageFolder = null;
        try {
            imageFolder = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File file = new File(imageFolder, "static/images/");
        File f = new File(file, fileName);
        try {
            //使用工具类方法
            uploadedImageFile.getImage().transferTo(f);
            BufferedImage img = ImageUtil.change2jpg(f);
            img = (BufferedImage) ImageUtil.resizeImage(img, 400, 300);
            if (img != null) {
                ImageIO.write(img, "jpg", f);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = new JsonObject();
        if (productInfo.getId().equals("")) productInfo.setId(null);
        //存储商品实体
        if (productInfo.getId() == null) {
            ProductInfo productInfo1 = productInfoService.save(productInfo);
            if (productInfo1 != null) {
                jsonObject.addProperty("msg", 1);//添加成功
            } else {
                jsonObject.addProperty("msg", 0);//添加失败
            }
        } else {
            ProductInfo productInfo1 = productInfoService.save(productInfo);
            if (productInfo1 != null) {
                jsonObject.addProperty("msg", 3);//修改成功
            } else {
                //TODO 先判断是否删除图片

                jsonObject.addProperty("msg", 2);//修改失败
            }
        }
        jsonObject.addProperty("openid", openid);
        return jsonObject.toString();
    }

    @RequestMapping("/productlistbyid")
    public ModelAndView categoryListById(String openid, Integer sortCode, ProductQuery productQuery, @RequestParam(value = "page", defaultValue = "1") int start, @RequestParam(value = "size", defaultValue = "2") int size) {
        if (sortCode != null) sortCodeForAdmin = sortCode;
        ModelAndView modelAndView = new ModelAndView();
        //进行分页
        Page<ProductInfo> page = productInfoService.findProductCrCriteria(start - 1, size, productQuery, sortCodeForAdmin);
        modelAndView.setViewName("productlist");
        modelAndView.addObject("page", page);
        modelAndView.addObject("sortCode", sortCodeForAdmin);
        modelAndView.addObject("currentPage", start - 1);
        modelAndView.addObject("size", size);
        modelAndView.addObject("openid", openid);
        return modelAndView;
    }

    @RequestMapping("/productlistbytime")
    public ModelAndView productListByTime(String openid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam(value = "page", defaultValue = "1") int start, @RequestParam(value = "size", defaultValue = "2") int size) {
        if (createTime != null) {
            createTimeForAdmin = createTime;
        }
        if (endTime != null) {
            endTimeForAdmin = endTime;
        }
        ModelAndView modelAndView = new ModelAndView();
        Page<ProductInfo> page = productInfoService.findProductByTime(createTimeForAdmin, endTimeForAdmin, start - 1, size);
        //返回视图
        modelAndView.setViewName("productlist");
        modelAndView.addObject("page", page);
        modelAndView.addObject("currentPage", start - 1);
        modelAndView.addObject("size", size);
        modelAndView.addObject("sortCode", 2);
        modelAndView.addObject("openid", openid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//要转换的时间格式
        if (createTimeForAdmin != null) {
            modelAndView.addObject("createTime", sdf.format(createTimeForAdmin));
        } else {
            modelAndView.addObject("createTime", "0000-00-00");
        }
        if (endTimeForAdmin != null) {
            modelAndView.addObject("endTime", sdf.format(endTimeForAdmin));
        } else {
            modelAndView.addObject("endTime", "0000-00-00");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/getcategorylist", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo getCategoryList(String openid) {
        List<ProductCategory> categoryList = categoryService.findAll();
        List<CategoryResult> categoryResultList = new ArrayList<CategoryResult>();
        for (ProductCategory productCategory : categoryList) {
            CategoryResult categoryResult = new CategoryResult();
            BeanUtils.copyProperties(productCategory, categoryResult);
            categoryResultList.add(categoryResult);
        }
        return ResultUtil.success(categoryResultList);
    }
}
